#include "sound.h"

QHash<QString, Phonon::MediaSource*> Sound::soundSources;
bool Sound::soundOn = true;
bool Sound::musicOn = true;

Sound::Sound() :
    QObject()
{
    musicObject = new Phonon::MediaObject();
    musicOutput = new Phonon::AudioOutput(Phonon::GameCategory);
    Phonon::Path path = Phonon::createPath(musicObject, musicOutput);
    connect(musicObject, SIGNAL(aboutToFinish()), this, SLOT(prepareMusicLoop()));
}

void Sound::initSounds() {
    QDir soundDir("sounds");
    QFileInfoList soundFiles = soundDir.entryInfoList();

    for(int i = 0; i < soundFiles.size(); ++i) {
        QFileInfo file = soundFiles[i];
        if(file.isFile() && (file.fileName().contains(".wav") || file.fileName().contains(".mp3"))) {
            soundSources[file.baseName()] = new Phonon::MediaSource("sounds/" + file.fileName());

            if(file.fileName().contains(".wav")) {
                playSound(file.baseName(), 0);
            }
        }
    }
}

void Sound::playSound(QString soundName, double volume) {
    if(soundOn) {
        Phonon::MediaObject *mediaObject = new Phonon::MediaObject();
        mediaObject->setCurrentSource(*soundSources[soundName]);

        Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::GameCategory);
        audioOutput->setVolume(volume);

        Phonon::Path path = Phonon::createPath(mediaObject, audioOutput);
        mediaObject->play();

        connect(mediaObject, SIGNAL(finished()), audioOutput, SLOT(deleteLater()));
        connect(mediaObject, SIGNAL(finished()), mediaObject, SLOT(deleteLater()));
    }
}

void Sound::setMusic(QString musicName, double volume) {
    musicObject->clear();
    musicObject->setCurrentSource(*soundSources[musicName]);
    musicOutput->setVolume(volume);
    musicObject->play();
}

void Sound::play() { musicObject->play(); }
void Sound::pause() { musicObject->pause(); }

bool Sound::soundEnabled() { return soundOn; }
bool Sound::musicEnabled() { return musicOn; }
void Sound::setSoundEnabled(bool b) { soundOn = b; }
void Sound::setMusicEnabled(bool b) { musicOn = b; }

void Sound::prepareMusicLoop() {
    musicObject->enqueue(musicObject->currentSource());
}
